package com.prime.tutorial.moviestore.view.auth;

import com.prime.tutorial.moviestore.Constants;
import com.prime.tutorial.moviestore.domain.UserActivity;
import com.prime.tutorial.moviestore.service.auth.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import java.util.Date;


/**
 * Provides logout
 * Created by IntelliJ IDEA.
 * Users: me
 * Date: 21 лют 2010
 * Time: 17:22:11
 * @author iryna.masyuk
 */
@Component("logout")
@Scope("request")
public class Logout {
    private AuthService authService;

    @Autowired
    public Logout(AuthService authService) {
        this.authService = authService;
    }

    public String logout(){
        //TODO test useractivity
        FacesContext context = FacesContext.getCurrentInstance();
        UserActivity userAct = (UserActivity)(context.getExternalContext().getSessionMap().get(Constants.USERACTIVITY_SESSION_KEY));
        userAct.setLogout(new Date());
        authService.updateUserActivity(userAct);

        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return "login";
    }
}
